package com.hm.service.impl.upload;

import com.alibaba.fastjson2.JSONObject;
import com.hm.service.framework.base.BaseServiceImpl;
import com.hm.service.service.upload.UploadPictureService;
import com.hm.service.utils.Md5Utils;
import com.hm.service.utils.PictureUtils;
import com.hm.service.utils.SoleIdUtils;
import com.hm.service.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.util.HashMap;


@Service
public class UploadPictureServiceImpl extends BaseServiceImpl implements UploadPictureService {

    private static final Logger logger = LoggerFactory.getLogger(UploadPictureServiceImpl.class);


    @Qualifier("JedisPool")
    private final JedisPool jedisPool;

    public UploadPictureServiceImpl(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public String getPermit(JSONObject jsonObject) {
        String timestamp = jsonObject.getString("timestamp");//时间戳
        String version = jsonObject.getString("version");//版本号
        String actionType = jsonObject.getString("actionType");//动作类型
        String params1 = jsonObject.getString("params1");//参数1
        String params2 = jsonObject.getString("params2");//参数2
        String params3 = jsonObject.getString("params3");//参数3
        String params4 = jsonObject.getString("params4");//参数4
        String signature = jsonObject.getString("signature");//签名
        //验证时间戳（前后不超过30秒）
        long timeDifference = TimeUtils.calculate(Long.parseLong(timestamp), System.currentTimeMillis());
        long limit = 1000 * 30;
        if (Math.abs(timeDifference) > limit) {
            //时间戳超时了
            return generateFail("timestamp超时");
        }
        //签名按照顺序timestamp->actionType->version->params3->params2->params4->params1->全小写再md5
        String s = timestamp.toLowerCase() + actionType.toLowerCase() + version.toLowerCase() + params3.toLowerCase() + params2.toLowerCase() + params4.toLowerCase() + params1.toLowerCase();
        String dynamicSignature = Md5Utils.generateMD5(s);
        if (signature == null || !signature.equals(dynamicSignature)) {
            return generateFail("无效signature");
        }
        HashMap<String, String> resMap = new HashMap<>();
        //try块退出时，会自动调用res.close()方法，关闭资源。
        try (Jedis jedis = jedisPool.getResource()) {
            //设置保存时间为30秒
            String permit = SoleIdUtils.getUUID();
            String currentTime = TimeUtils.getCurrentTime();
            jedis.setex(permit, 30, currentTime);
            //生成bean
            resMap.put("permit", permit);
            return generateSucceed(resMap);
        } catch (Exception e) {
            return generateFail("获取文件上传凭证失败：" + e.getMessage());
        }
    }

    @Override
    public String uploadPic(MultipartFile file, String permit) {
        if (permit == null) {
            return generateFail("上传凭证为空");
        }
        try (Jedis jedis = jedisPool.getResource()) {
            boolean exists = jedis.exists(permit);
            if (exists) {
                //凭证使用后马上失效
                jedis.del(permit);
            } else {
                //说明没有凭证
                return generateFail("非法上传");
            }
        }
        //1、处理创建文件夹
        String folderPath = createFolderPath();
        if (folderPath.isEmpty()) {
            return generateFail("服务器系统错误");
        }
        File folder = new File(folderPath);
        //不存在，则创建
        if (!folder.exists()) {
            boolean success = folder.mkdirs();
            logger.info("创建文件夹：{}", success ? "成功" : "失败");
            if (!success) {
                return generateFail("文件夹创建失败");
            }
        }
        //2、处理文件名
        if (file == null) {
            return generateFail("待上传文件为空");
        }
        String oldFileName = file.getOriginalFilename();
        if (oldFileName == null) {
            return generateFail("文件名为空");
        }
        //获取文件后缀名
        int index = oldFileName.lastIndexOf(".");
        if (index > 0) {
            String suffixName = oldFileName.substring(index);
            logger.info("文件后缀名：{}", suffixName);
            try {
                //文件保存
                String newName = SoleIdUtils.getUUID() + suffixName;
                File newFile = new File(folder, newName);
                file.transferTo(newFile);
                //构建返回参数
                HashMap<String, String> resMap = new HashMap<>();
                resMap.put("des", "上传成功");
                resMap.put("picUrl", PictureUtils.generateUrl("http://host:port/SZCG/IMAGE/facePic?id=" + newName));
                return generateSucceed(resMap);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        } else {
            return generateFail("文件后缀名格式错误");
        }
        return "文件后缀名格式错误！";
    }

    //创建文件夹路径
    private static String createFolderPath() {
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            // 当前操作系统为Windows
            return "D:/opencv-test/face-pic";
        }
        if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
            // 当前操作系统为Unix/Linux
            return "/root/001/002";
        }
        return "";
    }
}
